Grokking Amazon Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Amazon Easy Problems
Redistribute Characters to Make All Strings Equal (easy)
Solution: Redistribute Characters to Make All Strings Equal
Longest Common Prefix (easy)
Solution: Longest Common Prefix
Make Array Zero by Subtracting Equal Amounts (easy)
Solution: Make Array Zero by Subtracting Equal Amounts
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Path Crossing (easy)
Solution: Path Crossing
Special Array With X Elements Greater Than or Equal X (easy)
Solution: Special Array With X Elements Greater Than or Equal X
Relative Sort Array (easy)
Solution: Relative Sort Array
Transpose Matrix (easy)
Solution: Transpose Matrix
Find Common Characters (easy)
Solution: Find Common Characters
Fizz Buzz (easy)
Solution: Fizz Buzz
Increasing Order Search Tree (easy)
Solution: Increasing Order Search Tree
Largest Odd Number in String (easy)
Solution: Largest Odd Number in String
Best Time to Buy and Sell (easy)
Solution: Best Time to Buy and Sell Stock
Take Gifts From the Richest Pile(easy)
Solution: Take Gifts From the Richest Pile
Remove Duplicates from Sorted List (easy)
Solution: Remove Duplicates from Sorted List
Amazon Medium Problems
Maximum Length of Subarray With Positive Product (medium)
Solution: Maximum Length of Subarray With Positive Product
Largest Submatrix With Rearrangements (medium)
Solution: Largest Submatrix With Rearrangements
Count the Number of Good Subarrays (medium)
Solution: Count the Number of Good Subarrays
Minimum Suffix Flips (medium)
Solution: Minimum Suffix Flips
Minimum Number of Operations to Make Array Empty (medium)
Solution: Minimum Number of Operations to Make Array Empty
Next Greater Element II (medium)
Solution: Next Greater Element II
Make Sum Divisible by P (medium)
Solution: Make Sum Divisible by P
Rotting Oranges (medium)
Solution: Rotting Oranges
Minimum Deletions to Make Character Frequencies Unique (medium)
Solution: Minimum Deletions to Make Character Frequencies Unique
Minimum Adjacent Swaps to Make a Valid Array (medium)
Solution: Minimum Adjacent Swaps to Make a Valid Array
Reverse Integer (medium)
Solution: Reverse Integer
Maximize Distance to Closest Person (medium)
Solution: Maximize Distance to Closest Person
Split Linked List in Parts (medium)
Solution: Split Linked List in Parts
Maximum Difference Between Node and Ancestor (medium)
Solution: Maximum Difference Between Node and Ancestor
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
The kth Factor of n (medium)
Solution: The kth Factor of n
Coin Change II (medium)
Solution: Coin Change II
Sum of Subarray Minimums (medium)
Solution: Sum of Subarray Minimums
Valid Sudoku (medium)
Solution: Valid Sudoku
Longest Increasing Subsequence (medium)
Solution: Longest Increasing Subsequence
Next Permutation (medium)
Solution: Next Permutation
Subsets (medium)
Solution: Subsets
Combination Sum (medium)
Solution: Combination Sum
Number of Provinces (medium)
Solution: Number of Provinces
Number of Islands (medium)
Solution: Number of Islands
Constrained Subsequence Sum (hard)
Solution: Constrained Subsequence Sum
Number of Valid Subarrays (hard)
Solution: Number of Valid Subarrays
Count Vowels Permutation (hard)
Solution: Count Vowels Permutation
Concatenated Words (hard)
Solution: Concatenated Words
Minimum Replacements to Sort the Array (hard)
Solution: Minimum Replacements to Sort the Array
Count All Valid Pickup and Delivery Options (hard)
Solution: Count All Valid Pickup and Delivery Options
Length of the Longest Valid Substring (hard)
Solution: Length of the Longest Valid Substring
Count Array Pairs Divisible by K (hard)
Solution: Count Array Pairs Divisible by K
Word Ladder (hard)
Solution: Word Ladder
Path with Maximum Sum (hard)
Solution: Path with Maximum Sum
Solution: Largest Submatrix With Rearrangements

Problem Statement

You are given a binary matrix matrix of size m x n. You are allowed to shuffle the columns of the matrix in any order.

Return the area of the largest submatrix, whose all elements are 1 after shuffling the columns of the matrix.

Examples

Example 1:

  • Input:
[[1,0,1],
 [1,1,1],
 [1,0,1]]
  • Expected Output: 6
Image
  • Justification: By swapping the 2nd and 3rd columns, we can form a 2x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.

Example 2:

  • Input:
[[0,1],
 [1,1]]
  • Expected Output: 2
Image
  • Justification: The columns can be rearranged (although in this case, it's not necessary) to form the largest rectangle of 1s that is 1x2 or 2x1. The area is 2.

Example 3:

  • Input:
[[1,1,0,0],
 [1,0,1,1], 
 [1,1,1,1],
 [0,1,1,0]]
  • Expected Output: 6
Image
  • Justification: By swapping the 2nd and 4th column, we can form a 3x2 rectangle of 1s. It forms the largest rectangle of 1s with an area of 6.

Solution

To solve this problem, the algorithm first focuses on converting the given binary matrix into a histogram representation. This conversion involves calculating the height of consecutive 1s in each column, essentially transforming the problem into finding the largest area under the histogram for each row. The rationale behind this approach is that by considering each row as the base and the calculated heights as the potential heights of rectangles, we can explore the maximum area that can be formed by rearranging these heights, thus rearranging columns.

After converting the matrix into a histogram of heights, the next step involves sorting the heights in each row in descending order. This sorting allows for the efficient calculation of the maximum area for each row by multiplying the height of each column by its rank in the sorted order. The reason this approach is effective is that it aligns with the principle of maximizing the area under the histogram by utilizing the tallest columns together, ensuring the formation of the largest possible rectangle of 1s. This method is believed to be the most efficient as it reduces the problem to a series of histogram area calculations, which can be done in linear time per row after sorting.

Step-by-step algorithm

  • Step 1: Iterate through each cell of the matrix. For each cell that contains a 1, update its value to be the sum of itself and the value of the cell directly above it. This effectively calculates the height of consecutive 1s for each column.
  • Step 2: For each row in the transformed matrix, sort the values in non-increasing order. This rearranges the columns in a way that aligns taller columns together, simulating the optimal rearrangement for forming the largest rectangle.
  • Step 3: After sorting, iterate through each row's values. Multiply each value (height of the rectangle) by its index plus one (representing the width of the rectangle formed up to that column) to calculate the area of the rectangle that can be formed using that height.
  • Step 4: Keep track of the maximum area encountered during the iteration through all rows.
  • Step 5: Return the maximum area as the result.

Algorithm Walkthrough

Let's consider the input:

[[1,1,0,0],
 [1,0,1,1],
 [1,1,1,1],
 [0,1,1,0]]
  • Step 1: Convert to Heights Matrix

    • Starting from the second row, add the value of the current cell to the value above it if the current cell is 1. This computes the height of consecutive 1s for each column.
    • After processing, the matrix becomes:
      1 1 0 0
      2 0 1 1
      3 1 2 2
      0 2 3 0
      
    • Explanation: Each column now shows how many consecutive 1s are above, including the current cell.
  • Step 2: Sort Each Row in Non-Increasing Order

    • Sort the heights within each row to bring the highest potential for forming large rectangles to the forefront.
    • The matrix after sorting each row:
      1 1 0 0
      2 1 1 0
      3 2 2 1
      3 2 0 0
      
    • Explanation: By sorting, we align columns in a way that maximizes the potential area for each row's histogram.
  • Step 3: Calculate the Maximum Area for Each Row

    • For each row, calculate the area by multiplying each sorted height by its 1-based index (which represents the width of the rectangle that can be formed using that height).
    • For the third row (3 2 2 1), the areas calculated are 3*1=3, 2*2=4, 2*3=6, 1*4=4. The maximum area from this row is 6.
    • Perform this calculation for every row and track the overall maximum area.
  • Step 4: Identify the Maximum Area

    • After evaluating all rows, the maximum area found is 6, which is the answer for this example.
  • Final Output:

    • The algorithm concludes that the largest submatrix with rearrangements for the given example is 6.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity: The overall time complexity of the algorithm is , where (m) is the number of rows and (n) is the number of columns in the matrix. This complexity arises because, for each row, we sort the heights, which takes time, and we do this for all (m) rows.

Space Complexity: The space complexity of the algorithm is , which is required for sorting the heights in each row. No additional space proportional to the size of the input matrix is required beyond that, as the transformation and sorting are done in place.

Largest Submatrix With Rearrangements (medium)
Count the Number of Good Subarrays (medium)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-step algorithm

Algorithm Walkthrough

Code

Complexity Analysis